
layui.use(['form', 'layer', 'laydate', 'table', 'upload'], function(){

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        upload = layui.upload,
        table = layui.table;

    var detail_url = $('.detail_url').val();
    var search_cangku_url = $('.search_cangku_url').val();
    var get_cangkuproduct_url = $('.get_cangkuproduct_url').val();
    var save_beihuo_session_url = $('.save_beihuo_session_url').val();
    var order_track_url = $('.order_track_url').val();

    laydate.render({
        elem: '#test16',
        type: 'datetime',
        range: '到',
        format: 'yyyy年M月d日H时m分s秒'
    });


    // Table 列表
    var tableIns = table.render({
        elem: '#dataTable',
        url : detail_url,
        page : false,
        totalRow: true,
        cellMinWidth : 95,
        //height : "full-100",
        limit : 10,
        limits : [10, 20, 50, 100],
        id : "tableList",
        cols : [[
            {type: "checkbox", fixed:"left", width:50,LAY_CHECKED:true},
            {field: 'key', title: '序号', width:80, align:"center",totalRowText: '合计'},
            {field: 'product_name', title: '商品名称', minWidth:110},
            {field: 'bar_code', title: '条码', align:'center'},
            {field: 'spec', title: '规格', align:'center'},
            {field: 'count', title: '购买数量', align:'center', minWidth:110,totalRow: true},
            {field: 'unit', title: '单位', align:'center', minWidth:110},
            {field: 'price', title: '售价', align:'center', minWidth:110, templet:function(data){
                return '¥'+formatMoney(data.price/100,1)
            }},
            {field: 'total_price', title: '商品金额', align:'center', minWidth:110,totalRow: true},
            {field: 'beihuo_info', title: '发货批次详情(备货信息)', align:'center', minWidth:400},
            /*{title: '操作', minWidth:175, templet:'#handleBar', fixed:"right", align:"center"},*/
            {title: '仓库备货', fixed:"right", align:"center", minWidth:140, templet:function(data){
                var html = '';
                console.log(data.old_status)
                if(data.old_status == 2 && (data.after_sale_status == 0 || data.after_sale_status == 3 || data.after_sale_status == 5)){
                    html += '<a class="layui-btn layui-btn-xs layui-btn-normal" data-oid="'+data.order_id+'" lay-event="search_cangku"><i class="layui-icon layui-icon-search"></i>查询仓库</a>';
                }else if(data.after_sale_status == 1){
                    html += '<span style="color: red;">商品售后中</span>'
                }
                else if(data.after_sale_status == 2){
                    html += '<span style="color: red;">已经同意售后</span>'
                }
                else {
                    html += '-'
                }


                    return html;
                }}
        ]]
    });

    // Table 列表
    var tablecangkuproduct = table.render({
        elem: '#dataTable01',
        url : get_cangkuproduct_url,
        page : false,
        cellMinWidth : 95,
        //height : "full-100",
        id : "tableList",
        initSort: {
            field: 'production_time' // 排序字段，对应 cols 设定的各字段名
            ,type: 'asc' // 排序方式  asc: 升序、desc: 降序、null: 默认排序
        },
        cols : [[
            {type: "checkbox", fixed:"left", width:50,LAY_CHECKED:false},
            {field: 'product_name', title: '商品名称',align:'center'},
            {field: 'num', title: '存库', align:'center'},
            {field: 'production_time', title: '生产日期', align:'center'},
            {field: 'se_num', title: '发货数量（可编辑）', align:'center',edit:true},
            /*{title: '操作', minWidth:175, templet:'#handleBar', fixed:"right", align:"center"},*/


        ]]

    });

    table.on('edit(dataTable01)',function (e) {
        //编辑表格单元格
        if(!checkRate(e.value)){
            tablecangkuproduct.reload();
            layer.msg('发货数量必须大于0')
        }else {
            var value = e.value //得到修改后的值
                ,data = e.data //得到所在行所有键值
            var order_id = $('#order_id').val();
            console.log(data)
            if(value <= data.num){
                // $.ajax({
                //     url: edit_fahuonum_url,
                //     data: {"id": data.id,"value":value,'product_id':data.product_id,'order_id':order_id,'production_time':data.production_time},
                //     type: "POST",
                //     dataType: "json",
                //     success: function (res) {
                //         if (res.code == 1) {
                //             layer.msg('操作成功');
                //
                //         } else {
                //             layer.msg(res.msg);
                //             tablecangkuproduct.reload();
                //         }
                //     },
                //     error: function (data) {
                //         layer.msg("服务器无响应");
                //     }
                // });
            }else {
                layer.msg("发货数量应该小于库存");
                tablecangkuproduct.reload();
            }

        }


    })

    $('.selection').on('click',function () {
        var checkStatus = table.checkStatus('tableList'),
            data = checkStatus.data;
        //layer.closeAll();
        var temp = [];
        console.log(data)
        if(data.length > 0) {
            for (var i = 0;i<data.length;i++) {
                if(data[i].se_num > 0){
                    var datas = {
                        product_batch_stock_id: data[i].id,
                        product_id:data[i].product_id,
                        production_time:data[i].production_time,
                        se_num:data[i].se_num,
                    };
                    temp.push(datas)
                }


            }
            console.log(temp);
            $.ajax({
                url: save_beihuo_session_url,
                data: {temp},
                type: "POST",
                dataType: "json",
                success: function (res) {
                    if (res.code == 1) {
                        layer.closeAll();
                        tableIns.reload();
                    } else {
                        layer.msg(res.msg);
                        tablecangkuproduct.reload();
                    }
                },
                error: function (data) {
                    layer.msg("服务器无响应");
                }
            });
        }else {
            layer.msg("请选择某个生产日期的该商品，并填写发货数量");
        }


    });
    $('.confirm_beihuo').on('click',function () {
        var checkStatus = table.checkStatus('tableList');
        var data = checkStatus.data;
        console.log(data);

        if(data.length > 0){
            for (var i = 0;i<data.length;i++) {

                if(data[i].beihuo_info.trim() == ''){
                    layer.msg("所有商品必须备货");
                    return false;
                }
            }
            var order_id = data[0]['order_id']
            layer.alert('请仔细检查备货信息', {
                skin: 'layui-layer-molv' //样式类名  自定义样式
                ,closeBtn: 1    // 是否显示关闭按钮
                ,anim: 1 //动画类型
                ,title:'确认备货吗？'
                ,area: ['420px', '240px'] //宽高
                ,btn: ['确定'] //按钮
                ,icon: 7    // icon
                ,yes:function(){
                    $.ajax({
                        url: '/admin/Saleol/confirm_beihuo',
                        data: {'order_id':order_id},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            if (res.code == 1) {
                                layer.msg(res.msg);
                                window.location.href = res.url
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });
                }
            });
        }else {
            layer.msg("请选择");
        }
    });



    $('.confirm_peisong').on('click', function(){

        layer.open({
            type: 1
            , anim: 1
            , title: '配送信息'
            ,btn: ['确定']
            , closeBtn: 1
            , shade: 0.2
            , shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-Elasticframe'
            , area: ['600px','400px']
            , content: $('#peisong')
            ,yes: function(index, layero){
                var kuaidi = $('#kuaidiselect').val();
                var kuaidino = $('#kuaidino').val();
                var order_id = $('#order_id').val();
                if(kuaidi == 0){
                    layer.msg('请选择快递公司');
                }else if(kuaidino.trim() == ''){
                    layer.msg('请填写正确的快递单号');
                }else {
                    $.ajax({
                        url: '/admin/Saleol/save_wuliu',
                        data: {'order_id':order_id,'kuaidi':kuaidi,'kuaidino':kuaidino},
                        type: "POST",
                        dataType: "json",
                        success: function (res) {
                            if (res.code == 1) {
                                layer.msg(res.msg);
                                layer.close(index);
                                setTimeout(function () {
                                    window.location.href = res.url
                                }, 2000)
                                //
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function (data) {
                            layer.msg("服务器无响应");
                        }
                    });

                }
                //按钮【按钮一】的回调
            }
        });
        $(".layui-layer-shade").css("display","none");
        //其中：layero是弹层的DOM对象
        // $('#view-modal').modal('toggle');

    });


    $('.order_track').on('click', function(){
        var order_id = $('#order_id').val();
        var content = '/admin/Saleol/order_track/order_id/' + order_id
        var index = layer.open({
            type: 2
            , anim: 1
            , title: '订单轨迹'
            , shade: 0.2
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: ['900px','700px']
            , top: 0
            , content: content
        });

    });


    // 列表操作
    table.on('tool(dataTable)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        console.log(obj)
        // 删除
        if(layEvent === 'search_cangku'){
                formHtml(data);
        }
    });

    // Form 表单
    function formHtml(data){


        var content = search_cangku_url + '?productid=' + data.product_id + '&order_id=' + data.order_id

        // 右侧面板
        var index = layer.open({
            type: 2
            , anim: 1
            , title: '仓库'
            , shade: 0.2
            //, shadeClose: true // 是否点击遮罩关闭
            , skin: 'layui-anim layui-anim-rl layui-layer-adminRight'
            , area: ['900px','700px']
            , top: 0
            , content: content
            ,end:function () {
                tableIns.reload();
            }
        });
    }


});